package com.cnpinxi.service;

import com.cnpinxi.dao.ShoppingCartDao;
import com.cnpinxi.domain.ResourceRelation;
import com.cnpinxi.domain.ShoppingCart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Baggio on 2018-2-1.
 */
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    ShoppingCartDao shoppingCartDao;  @Autowired
    ResourceRelationService resourceRelationService;

    private int insertShoppingCart(ShoppingCart record) {
         shoppingCartDao.insertShoppingCart(record);
        return 0;
    }


    private int updateShoppingCartById(ShoppingCart record) {
        shoppingCartDao.updateShoppingCartById(record);
        return 0;
    }

    @Override
    public List<ShoppingCart> selectShoppingCartList(Map<String, String> map) {
        List<ShoppingCart> shoppingCartList=shoppingCartDao.selectShoppingCartList(map);
        for (ShoppingCart shoppingCart:shoppingCartList
             ) {

            map.put("resourceRelationId",String.valueOf(shoppingCart.getProductEntityId()));
            map.put("resourceRelationType",String.valueOf(ResourceRelation.RESOURCE_RELATION_TYPE_ORDER));
          List<ResourceRelation> resourceRelationList=  resourceRelationService.getResourceRelationList(map);
            shoppingCart.getProductEntity().setResourceRelationList(resourceRelationList);
        }
        return shoppingCartList;
    }

    @Override
    public ShoppingCart selectShoppingCart(Map<String, String> map) {
        return shoppingCartDao.selectShoppingCart(map);
    }

    @Override
    public void deleteShoppingCart(Map<String, String> map) {
        shoppingCartDao.deleteShoppingCart(map);

    }

    @Override
    public void modifyShoppingCart(ShoppingCart shoppingCart) {

        if(shoppingCart.getTid()==null){
            shoppingCart.setCreateTime(new Date());
            insertShoppingCart(shoppingCart);
            return;
        }
        Map<String,String> map=new HashMap<>();
        map.put("shoppingCartId",String.valueOf(shoppingCart.getTid()));
        ShoppingCart shoppingCart1=shoppingCartDao.selectShoppingCart(map);
        if(shoppingCart.getAmount()>0){
            shoppingCart1.setAmount(shoppingCart.getAmount());
        }
        updateShoppingCartById(shoppingCart1);
    }
}
